package com.huluobo.higt4demo1911.ui.main;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.media.Image;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.NetworkUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.huluobo.higt4demo1911.R;
import com.huluobo.higt4demo1911.core.mvp.BaseFragment;
import com.huluobo.higt4demo1911.core.mvp.IPresenter;

import io.agora.rtc.Constants;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import top.littlefogcat.danmakulib.danmaku.Danmaku;
import top.littlefogcat.danmakulib.danmaku.DanmakuManager;

import static com.blankj.utilcode.util.ViewUtils.runOnUiThread;

/**
 * 页面占位
 * Created by lc on 2022/4/22.
 */
public class LiveFragment extends BaseFragment<IPresenter> {

    private DanmakuManager danmakuManager;
    private FrameLayout mFrameLayout, good_layout;
    private EditText danmuEd;

    private Button startLiveBtn, leaveBtn, sendBtn, sendGiftBtn;
    private static final int PERMISSION_REQ_ID = 22;

    private LinearLayout giftLayout;

    private static final String[] REQUESTED_PERMISSIONS = {
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA
    };

    private boolean checkSelfPermission(String permission, int requestCode) {
        if (ContextCompat.checkSelfPermission(getContext(), permission) !=
                PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(getActivity(), REQUESTED_PERMISSIONS, requestCode);
            return false;
        }
        return true;
    }

    // 填写你的项目在 Agora 控制台中生成的 App ID。
    private String appId = "dcf26be7568447a28c005903515eed89";
    // 填写频道名称。
    private String channelName = "123";
    // 填写 Agora 控制台中生成的临时 Token。
    private String token = "006dcf26be7568447a28c005903515eed89IAAPDoX/Lb1slF1midDMe49A/0yxlQAbyb8ylms343vrjtJjSIgAAAAAEAA4pEgwJNJ1YgEAAQAi0nVi";

    private RtcEngine mRtcEngine;

    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {
        @Override
        // 监听频道内的远端主播，获取主播的 uid 信息。
        public void onUserJoined(int uid, int elapsed) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    // 从 onUserJoined 回调获取 uid 后，调用 setupRemoteVideo，设置远端视频视图。
//                    setupRemoteVideo(uid);
                }
            });
        }
    };

    private void initializeAndJoinChannel() {
        try {
            mRtcEngine = RtcEngine.create(getContext(), appId, mRtcEventHandler);
        } catch (Exception e) {
            throw new RuntimeException("Check the error.");
        }

        // 直播场景下，设置频道场景为 BROADCASTING。
        mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
        // 根据场景设置用户角色为 BORADCASTER 或 AUDIENCE。
        mRtcEngine.setClientRole(Constants.CLIENT_ROLE_BROADCASTER);

        // 视频默认禁用，你需要调用 enableVideo 开始视频流。
        mRtcEngine.enableVideo();

        FrameLayout container = findViewById(R.id.local_video_view_container);
        // 调用 CreateRendererView 创建一个 SurfaceView 对象，并将其作为 FrameLayout 的子对象。
        SurfaceView surfaceView = RtcEngine.CreateRendererView(getContext());
        container.addView(surfaceView);
        // 将 SurfaceView 对象传入 Agora，以渲染本地视频。
        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_FIT, 0));

        // 使用 Token 加入频道。
        mRtcEngine.joinChannel(token, channelName, "", 0);
    }


    @Override
    public int bindLayout() {
        return R.layout.fragment_live;
    }

    @Override
    public void initView() {
        startLiveBtn = findViewById(R.id.startLive);
        leaveBtn = findViewById(R.id.leave);
        mFrameLayout = findViewById(R.id.local_video_view_container);
        //弹幕初始化
        danmakuManager = DanmakuManager.getInstance();
        danmakuManager.init(getContext(), mFrameLayout);
        danmuEd = findViewById(R.id.live_danmuku_ed);
        sendBtn = findViewById(R.id.live_send_danmu);

        giftLayout = findViewById(R.id.gift_layout);
        sendGiftBtn = findViewById(R.id.sendGift);

        good_layout = findViewById(R.id.good_layout);
    }

    private boolean isClick = false;


    @SuppressLint("ClickableViewAccessibility")
    @Override
    public void initData() {
        startLiveBtn.setOnClickListener(v -> {
            // 如果已经授予所有权限，初始化 RtcEngine 对象并加入一个频道。
            if (checkSelfPermission(REQUESTED_PERMISSIONS[0], PERMISSION_REQ_ID) &&
                    checkSelfPermission(REQUESTED_PERMISSIONS[1], PERMISSION_REQ_ID)) {
                initializeAndJoinChannel();
            }
        });

        leaveBtn.setOnClickListener(v -> {
            mRtcEngine.leaveChannel();
            mRtcEngine.destroy();
        });

        sendBtn.setOnClickListener(v -> {
            if (!TextUtils.isEmpty(danmuEd.getText().toString())) {
                initDanmu(danmuEd.getText().toString());
                danmuEd.setText("");
            }
        });

        sendGiftBtn.setOnClickListener(v -> {
            sendGift(R.mipmap.cag);
        });

        good_layout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    //双击触发,固定时间内点击两次
                    if (!isClick) {
                        //没点过
                        isClick = true;
                        //开启还原方法
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                if (isClick) {
                                    try {
                                        Thread.sleep(300);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                                isClick = false;
                            }
                        }).start();

                    } else {
                        isClick = false;
                        //触发点赞的效果
                        Log.i("TagA", "isClick:" + isClick);
                        clickGood(new Point((int) event.getX(), (int) event.getY()));
                    }
                }
                return true;
            }
        });
    }

    private void initDanmu(String msg) {
        //弹幕对象
        Danmaku danmaku = new Danmaku();
        danmaku.text = msg;
        danmaku.size = SizeUtils.sp2px(20);
        //send
        danmakuManager.send(danmaku);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mRtcEngine.leaveChannel();
        mRtcEngine.destroy();


    }

    private void sendGift(int id) {
        ImageView giftView = new ImageView(getContext());
        giftView.setImageResource(id);
        giftView.setBackgroundColor(Color.parseColor("#55000000"));
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(300, 80);
        giftView.setLayoutParams(params);

        //礼物飞出的动画
        ObjectAnimator animatorOut = ObjectAnimator.ofFloat(giftView, "TranslationX", -300, 0);
        animatorOut.setDuration(1000);
        //相当于在画面中常驻2秒
        ObjectAnimator animatorShow = ObjectAnimator.ofFloat(giftView, "Alpha", 1, 1);
        animatorShow.setDuration(2000);
        ObjectAnimator animatorHide = ObjectAnimator.ofFloat(giftView, "Alpha", 1, 0);
        animatorHide.setDuration(1000);

        AnimatorSet set = new AnimatorSet();
        set.play(animatorShow).after(animatorOut).before(animatorHide);
//        set.play(animatorOut).before(animatorHide);
        set.start();

        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                giftLayout.removeView(giftView);
            }
        });

        giftLayout.addView(giftView);
    }

    private void clickGood(Point point) {
        ImageView goodIv = new ImageView(getContext());
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(300, 300);
        params.leftMargin = point.x - 150;
        params.topMargin = point.y - 150;
        goodIv.setLayoutParams(params);
        goodIv.setImageResource(R.mipmap.cab);

        ObjectAnimator animatorX = ObjectAnimator.ofFloat(goodIv, "ScaleX", 1, 2);
        ObjectAnimator animatorY = ObjectAnimator.ofFloat(goodIv, "ScaleY", 1, 2);
        ObjectAnimator animatorHide = ObjectAnimator.ofFloat(goodIv, "Alpha", 1, 0);

        AnimatorSet set = new AnimatorSet();
        set.setDuration(2000);
        set.play(animatorX).with(animatorY).with(animatorHide);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                good_layout.removeView(goodIv);
            }
        });
        set.start();
        good_layout.addView(goodIv);

    }


}
